package com.tangruojie.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 请求日志过滤器
 */
@Component
public class RequestLogFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestLogFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        // 记录请求信息
        String requestInfo = String.format(
                "Method: %s, URI: %s, RemoteAddr: %s",
                httpRequest.getMethod(),
                httpRequest.getRequestURI(),
                httpRequest.getRemoteAddr()
        );
        logger.info("Incoming Request: {}", requestInfo);
        // 记录请求开始时间（用于计算耗时）
        long startTime = System.currentTimeMillis();
        try {
            // 继续执行过滤器链
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 计算并记录请求处理耗时
            long duration = System.currentTimeMillis() - startTime;
            logger.info("Request {} completed in {} ms", httpRequest.getRequestURI(), duration);
        }
    }

}
